package com.sa.app.fragments;

import java.util.List;

import android.app.ActionBar;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.sa.app.R;
import com.sa.app.activities.MainActivity;
import com.sa.app.utilities.AsynchronousDownloaderXML;
import com.sa.app.utilities.AsynchronousInsertUse;
import com.sa.app.utilities.MyApplication;

public class HomeFragment extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		MainActivity ma = ((MainActivity) getActivity());
		List<String> ltd = ma.getInformationToDownload();
		if (!ltd.isEmpty()) {

			new AsynchronousDownloaderXML(ma, inflater.getContext(),
					ma.getDataBaseManager(), ltd.get(0), ltd.get(2), ltd.get(3))
					.execute(ma.getInformationToDownload().get(1));
			// Cuidado con la siguiente linea, al ser tarea asincrona la que usa
			// la lista, no sabemos exactamente si se vacia antes de la cuenta;
			ltd.clear();
		} else if (!ma.getGoToMeFromDataBase().isEmpty()) {

			new AsynchronousInsertUse(ma, inflater.getContext(), getActivity()
					.getApplication(), ma.getGoToMeFromDataBase(),
					MyApplication.TAGGED, "").execute("");
			ma.setGoToMeFromDataBase("");
		}

		View v = inflater.inflate(R.layout.home_view, null);
		if (((ViewGroup) v.getParent()) != null) {
			((ViewGroup) v.getParent()).removeView(v);
		}
		return v;

	}

	@Override
	public void onResume() {
		super.onResume();

	}

	@Override
	public void onPause() {
		super.onPause();

		// Restaurar actionbar

		LayoutInflater factory = getActivity().getLayoutInflater();
		View vf = factory.inflate(R.layout.actionbarview, null);

		ActionBar bar = getActivity().getActionBar();
		bar.setDisplayShowTitleEnabled(false);
		TextView title = (TextView) vf.findViewById(R.id.act_title);

		((ViewGroup) title.getParent()).removeView(title);
		bar.setDisplayShowCustomEnabled(true);
		bar.setCustomView((View) title);
	}

	// Esto hace que no cuelgue la aplicación al cambiar de activity utilizando
	// la libreria de compatibilidad
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		setUserVisibleHint(true);
	}
}